<template>
  <div :class="prefixCls" :style="{ width: containerWidth }">
    <textarea
      :id="tinymceId"
      ref="elRef"
      :style="{ visibility: 'hidden' }"
      v-if="!initOptions.inline"
    ></textarea>
    <slot v-else></slot>
  </div>
</template>

<script lang="ts" setup>
  // //引入类型
  // import type { Editor } from 'tinymce';
  import type { RawEditorOptionsType } from './tinymce';
  //在js中引入所需的主题和组件
  import tinymce from 'tinymce/tinymce';
  // import 'tinymce/skins/content/default/content.css';  //导入该样式后会引起页面排版错乱，暂注释。
  import 'tinymce/themes/silver';
  import 'tinymce/themes/silver/theme';
  import 'tinymce/icons/default'; //引入编辑器图标icon，不引入则不显示对应图标
  import 'tinymce/icons/default/icons';
  import 'tinymce/models/dom'; // 这里是个坑 一定要引入

  //在TinyMce.vue中引入相关插件
  // new URL('resource/tinymce/plugins/advlist', import.meta.url).href; //高级列表插件
  import 'tinymce/plugins/advlist'; //高级列表插件
  import 'tinymce/plugins/anchor'; //锚点插件
  import 'tinymce/plugins/autolink'; //自动链接插件
  import 'tinymce/plugins/autoresize'; //编辑器大小自适应
  import 'tinymce/plugins/autosave'; //自动存稿
  import 'tinymce/plugins/charmap'; //特殊字符插件
  import 'tinymce/plugins/code'; //编辑源码
  import 'tinymce/plugins/codesample'; //代码示例插件
  import 'tinymce/plugins/directionality'; //文字方向：设置文字从左到右或从右到左
  // import 'tinymce/plugins/emoticons'; //表情插件
  import 'tinymce/plugins/fullscreen'; //全屏
  import 'tinymce/plugins/help'; //帮助
  import 'tinymce/plugins/image'; //插入编辑图片插件
  import 'tinymce/plugins/importcss'; //引入css
  // import 'tinymce/plugins/insertdatetime'; //插入当前日期时间
  import 'tinymce/plugins/link'; //超链接
  import 'tinymce/plugins/lists'; //列表插件
  import 'tinymce/plugins/media'; //插入编辑媒体
  import 'tinymce/plugins/nonbreaking'; //插入不间断空格
  import 'tinymce/plugins/pagebreak'; //插入分页符
  import 'tinymce/plugins/preview'; //预览
  import 'tinymce/plugins/quickbars'; //快速工具栏
  import 'tinymce/plugins/save'; //保存
  import 'tinymce/plugins/searchreplace'; //查找替换
  import 'tinymce/plugins/table'; //表格插件
  // import 'tinymce/plugins/template'; //内容模板
  import 'tinymce/plugins/wordcount'; // 字数统计插件
  // import 'tinymce/plugins/visualblocks';
  // import 'tinymce/plugins/visualchars';

  // import '@npkg/tinymce-plugins/letterspacing'; //设置间距插件。可以设置文档中的文字间距
  // import '@npkg/tinymce-plugins/indent2em'; //首行缩进插件。提供中文段落排版的首行缩进2个字符的功能。增强优化 加入字间距非默认情况，也能实现准确首行缩进2字符；
  // import '@npkg/tinymce-plugins/importword'; //导入word插件。可以直接导入word ,并且保证word中图片不会丢失，自动转为base64;
  // import '@npkg/tinymce-plugins/imagetools'; //图片编辑工具插件， 对图片进行处理。优化跨域，功能更丰富；
  // import '@npkg/tinymce-plugins/table'; //表格插件，处理表格。 增强优化表格控制，增加表格转图片功能，便捷布局按钮；
  // import '@npkg/tinymce-plugins/bdmap'; //百度地图。 支持更改尺寸，自定义标签，开启导航功能,支持vue;
  // import '@npkg/tinymce-plugins/attachment'; //百度地图。 支持更改尺寸，自定义标签，开启导航功能,支持vue;

  import {
    computed,
    nextTick,
    ref,
    unref,
    watch,
    onDeactivated,
    onBeforeUnmount,
    PropType,
    useAttrs,
  } from 'vue';
  import { plugins as defaultPlugins, toolbar as defaultToolbar } from './tinymce';
  import { buildShortUUID } from '@/utils/uuid';
  import { bindHandlers } from './helper';
  import { onMountedOrActivated } from '@vben/hooks';
  import { useDesign } from '@/hooks/web/useDesign';
  import { isNumber, isString, isArray } from '@/utils/is';
  import { useLocale } from '@/locales/useLocale';
  import { useAppStore } from '@/store/modules/app';

  defineOptions({ name: 'Tinymce', inheritAttrs: false });

  const props = defineProps({
    /** 配置项 */
    options: {
      type: Object as PropType<Partial<RawEditorOptionsType>>,
      default: () => ({}),
    },
    /** 双向绑定的值 */
    value: {
      type: String,
      default: () => {
        return '';
      },
    },
    /** 回调失败的默认语言 */
    fallbackLang: { type: String, default: undefined },
    /** 菜单栏 */
    menubar: {
      type: [Boolean, String] as PropType<boolean | string>,
      default: undefined,
    },
    /** 工具栏 */
    toolbar: {
      type: [Boolean, String, Array] as PropType<
        | boolean
        | string
        | string[]
        | Array<{
            name?: string;
            items: string[];
          }>
      >,
      default: defaultToolbar,
    },
    /** 插件 */
    plugins: {
      type: [String, Array] as PropType<string | string[]>,
      default: defaultPlugins,
    },
    /** 限定编辑器的最小高度。 */
    minHeight: { type: Number, default: 360 },
    /** 限定编辑器的最大高度，当内容不断增长达到此高度时，编辑器将停止增加高度。 */
    maxHeight: { type: Number, default: undefined },
    /** 高度 */
    height: {
      type: [Number, String] as PropType<string | number>,
      required: false,
      default: 'auto',
    },
    /** 宽度 */
    width: {
      type: [Number, String] as PropType<string | number>,
      required: false,
      default: 'auto',
    },
  });

  const emit = defineEmits(['change', 'update:value', 'inited', 'init-error']);

  const attrs = useAttrs();
  // const editorRef = ref<Editor | null>(null);
  const fullscreen = ref(false);
  const tinymceId = ref<string>(`${buildShortUUID('tiny-vue')}_${Date.now()}`);
  const elRef = ref<HTMLElement | null>(null);

  const { prefixCls } = useDesign('tinymce-container');

  const appStore = useAppStore();

  //#region "容器宽度"
  const containerWidth = computed(() => {
    const width = props.width;
    if (isNumber(width)) {
      return `${width}px`;
    }
    return width;
  });
  //#endregion
  //#region "获取高度设置"
  const getHeight = computed(() => {
    const height = props.height;
    if (height === 'auto') {
      return undefined;
    }
    return height;
  });
  //#endregion
  //#region "获取插件"
  const getPlugins = computed(() => {
    const { height, plugins } = props;
    if (height === 'auto') {
      if (isString(plugins)) {
        return `${plugins} autoresize`;
      } else if (isArray(plugins)) {
        plugins.push('autoresize');
      }
    }
    return plugins;
  });
  //#endregion
  //公共文件夹路径
  const publicPath = computed(() => import.meta.env.VITE_PUBLIC_PATH || '/');
  //#region "皮肤"
  const skinName = computed(() => {
    return appStore.getDarkMode === 'light' ? 'oxide' : 'oxide-dark';
  });
  const skinUrl = computed(() => {
    if ((skinName.value !== undefined && skinName.value !== null) || skinName.value !== '') {
      return `${publicPath.value}resource/tinymce/skins/ui/${skinName.value}`;
    }
    return undefined;
  });
  const contentCss = computed(() => {
    if ((skinName.value !== undefined && skinName.value !== null) || skinName.value !== '') {
      return `${publicPath.value}resource/tinymce/skins/ui/${skinName.value}/content.min.css`;
    }
    return undefined;
  });
  //#endregion
  //#region "语言"
  const langName = computed(() => {
    const lang = useLocale().getLocale.value;
    let tinymceLang = props.fallbackLang;
    switch (lang) {
      case 'ar-AE':
        tinymceLang = 'ar';
        break;
      case 'az-AZ':
        tinymceLang = 'az';
        break;
      case 'bg-BG':
        tinymceLang = 'bg_BG';
        break;
      case 'bn-BD':
        tinymceLang = 'bn_BD';
        break;
      case 'ca-CA':
        tinymceLang = 'ca';
        break;
      case 'cs-CZ':
        tinymceLang = 'cs';
        break;
      case 'cy-GB':
        tinymceLang = 'cy';
        break;
      case 'da-DK':
        tinymceLang = 'da';
        break;
      case 'de-DE':
        tinymceLang = 'de';
        break;
      case 'dv-DV':
        tinymceLang = 'dv';
        break;
      case 'el-GR':
        tinymceLang = 'el';
        break;
      case 'en-US':
        tinymceLang = 'eu';
        break;
      case 'en-GB':
        tinymceLang = 'eu';
        break;
      case 'es-ES':
        tinymceLang = 'es';
        break;
      case 'et-EE':
        tinymceLang = 'et';
        break;
      case 'eu-ES':
        tinymceLang = 'eu';
        break;
      case 'fa-IR':
        tinymceLang = 'fa';
        break;
      case 'fi-FI':
        tinymceLang = 'fi';
        break;
      case 'fr-FR':
        tinymceLang = 'fr_FR';
        break;
      case 'ga-IE':
        tinymceLang = 'ga';
        break;
      case 'gl-ES':
        tinymceLang = 'gl';
        break;
      case 'he-IL':
        tinymceLang = 'he_IL';
        break;
      case 'hi-IN':
        tinymceLang = 'hi';
        break;
      case 'hr-HR':
        tinymceLang = 'hr';
        break;
      case 'hu-HU':
        tinymceLang = 'hu_HU';
        break;
      case 'hy-AM':
        tinymceLang = 'hy';
        break;
      case 'id-ID':
        tinymceLang = 'id';
        break;
      case 'is-IS':
        tinymceLang = 'is_IS';
        break;
      case 'it-IT':
        tinymceLang = 'it';
        break;
      case 'ja-JP':
        tinymceLang = 'ja';
        break;
      case 'kab-DZ':
        tinymceLang = 'kab';
        break;
      case 'kk-KZ':
        tinymceLang = 'kk';
        break;
      case 'ko-KR':
        tinymceLang = 'ko_KR';
        break;
      case 'ckb-IR':
        // tinymceLang = '';
        break;
      case 'lt-LT':
        tinymceLang = 'lt';
        break;
      case 'lv-LV':
        tinymceLang = 'lv';
        break;
      case 'nb-NB':
        // tinymceLang = '';
        break;
      case 'nb-NO':
        tinymceLang = 'nb_NO';
        break;
      case 'ne-NP':
        tinymceLang = 'ne';
        break;
      case 'nl-NL':
        tinymceLang = 'nl';
        break;
      case 'nl-BE':
        tinymceLang = 'nl_BE';
        break;
      case 'oc-OC':
        tinymceLang = 'oc';
        break;
      case 'pl-PL':
        tinymceLang = 'pl';
        break;
      case 'pt-PT':
        // tinymceLang = '';
        break;
      case 'pt-BR':
        tinymceLang = 'pt_BR';
        break;
      case 'ro-RO':
        tinymceLang = 'ro';
        break;
      case 'ru-RU':
        tinymceLang = 'ru';
        break;
      case 'sk-SK':
        tinymceLang = 'sk';
        break;
      case 'sl-SL':
        tinymceLang = 'sl_SI';
        break;
      case 'sq-AL':
        tinymceLang = 'sq';
        break;
      case 'sr-cyrl-RS':
        tinymceLang = 'sr';
        break;
      case 'sv-SE':
        tinymceLang = 'sv_SE';
        break;
      case 'ta-IN':
        tinymceLang = 'ta';
        break;
      case 'tg-TJ':
        tinymceLang = 'tg';
        break;
      case 'th-TH':
        tinymceLang = 'th_TH';
        break;
      case 'tr-TR':
        tinymceLang = 'tr';
        break;
      case 'ug-CN':
        tinymceLang = 'ug';
        break;
      case 'uk-UK':
        tinymceLang = 'uk';
        break;
      case 'vi-VN':
        tinymceLang = 'vi';
        break;
      case 'zh-CN':
        tinymceLang = 'zh_CN';
        break;
      case 'zh-TW':
        tinymceLang = 'zh_TW';
        break;
    }
    return tinymceLang;
  });
  const languageUrl = computed(() => {
    if ((langName.value !== undefined && langName.value !== null) || langName.value !== '') {
      return `${publicPath.value}resource/tinymce/langs/${langName.value}.js`;
    }
    return undefined;
  });
  //#endregion

  //初始化配置项
  const initOptions = computed((): RawEditorOptionsType => {
    const { options, menubar, toolbar, minHeight, maxHeight } = props;
    return {
      base_url: `${publicPath.value}resource/tinymce`,
      selector: `#${unref(tinymceId)}`, //selector是TinyMCE的重要配置选项，使用CSS选择器语法来确定页面上哪个元素被TinyMCE替换成编辑器
      menubar, //菜单栏
      toolbar, //工具栏
      plugins: getPlugins.value, //插件
      min_height: minHeight,
      max_height: maxHeight,
      height: getHeight.value, //编辑器高度
      language_url: languageUrl.value, //语言包的路径，具体路径看自己的项目，文档后面附上中文js文件
      language: langName.value, //语言
      skin_url: skinUrl.value, //皮肤路径，具体路径看自己的项目
      skin: skinName.value, //皮肤
      elementpath: false, // 隐藏底栏的元素路径
      promotion: false, //提示升级
      // image_dimensions: false, //去除宽高属性
      // branding: false, //是否禁用“Powered by TinyMCE”
      default_link_target: '_blank',
      link_title: false,
      object_resizing: false,
      auto_focus: true,
      content_css: contentCss.value,
      ...options,
      setup: (editor: any) => {
        // editorRef.value = editor;
        // console.log('setup', editor);
        editor.on('init', (e: any) => initSetup(e));
      },
      license_key: 'gpl',
    };
  });

  // const disabled = computed(() => {
  //   const { options } = props;
  //   const getDisabled = options && Reflect.get(options, 'readonly');
  //   // const editor = unref(editorRef);
  //   const editor = tinymce.get(unref(tinymceId));
  //   if (editor) {
  //     editor.mode.set(getDisabled ? 'readonly' : 'design');
  //   }
  //   return getDisabled ?? false;
  // });

  watch(
    () => attrs.disabled,
    () => {
      // tinymce.Editor['编辑器id'].setMode('design'); //开启编辑模式
      // tinymce.Editor['编辑器id'].setMode('readonly'); //开启只读模式
      // const editor = unref(editorRef);
      const editor = tinymce.get(unref(tinymceId));
      if (!editor) {
        return;
      }
      editor.mode.set(attrs.disabled ? 'readonly' : 'design');
    },
  );

  watch(
    () => appStore.getDarkMode,
    () => {
      // const editor = unref(editorRef);
      const editor = tinymce.get(unref(tinymceId));
      if (!editor) {
        return;
      }
      // 使用getContent() 在某处保存当前内容
      // const editorContent = editor.getContent();
      // 使用destroy() 销毁 TinyMCE 实例
      editor.destroy();
      // 重新初始化
      tinymce.init(unref(initOptions));
    },
  );

  onMountedOrActivated(() => {
    if (!initOptions.value.inline) {
      tinymceId.value = `${buildShortUUID('tiny-vue')}_${Date.now()}`;
    }
    nextTick(() => {
      setTimeout(() => {
        initEditor();
      }, 30);
    });
  });

  onBeforeUnmount(() => {
    destory();
  });

  onDeactivated(() => {
    destory();
  });

  function destory() {
    if (tinymce !== null) {
      tinymce?.remove?.(unref(initOptions).selector!);
    }
  }

  function initEditor() {
    const el = unref(elRef);
    if (el) {
      el.style.visibility = '';
    }
    tinymce
      .init(unref(initOptions))
      .then((editor) => {
        emit('inited', editor);
      })
      .catch((err) => {
        emit('init-error', err);
      });
  }

  function initSetup(e: any) {
    // const editor = unref(editorRef);
    const editor = tinymce.get(unref(tinymceId));
    if (!editor) {
      return;
    }
    const value = props.value || '';

    editor.setContent(value);
    bindModelHandlers(editor);
    bindHandlers(e, attrs, editor);

    //TODO:定义只读模式下双击可全屏
    // if (editor.options.get('readonly')) {
    //   const bodyElement = editor.getBody();
    //   bodyElement.addEventListener('dblclick', () => {
    //     editor.execCommand('mceFullScreen');
    //   });
    // }
  }

  function setValue(editor: Record<string, any>, val?: string, prevVal?: string) {
    if (
      editor &&
      typeof val === 'string' &&
      val !== prevVal &&
      val !== editor.getContent({ format: attrs.outputFormat })
    ) {
      editor.setContent(val);
    }
  }

  function bindModelHandlers(editor: any) {
    const modelEvents = attrs.modelEvents ? attrs.modelEvents : null;
    const normalizedEvents = Array.isArray(modelEvents) ? modelEvents.join(' ') : modelEvents;

    watch(
      () => props.value,
      (val, prevVal) => {
        setValue(editor, val, prevVal);
      },
    );

    watch(
      () => props.value,
      (val, prevVal) => {
        setValue(editor, val, prevVal);
      },
      {
        immediate: true,
      },
    );

    editor.on(normalizedEvents ? normalizedEvents : 'change keyup undo redo', () => {
      const content = editor.getContent({ format: attrs.outputFormat });
      emit('update:value', content);
      emit('change', content);
    });

    editor.on('FullscreenStateChanged', (e: any) => {
      fullscreen.value = e.state;
    });
  }

  // function handleImageUploading(name: string) {
  //   // const editor = unref(editorRef);
  //   const editor = tinymce.get(unref(tinymceId));
  //   if (!editor) {
  //     return;
  //   }
  //   editor.execCommand('mceInsertContent', false, getUploadingImgName(name));
  //   const content = editor?.getContent() ?? '';
  //   setValue(editor, content);
  // }

  // function handleDone(name: string, url: string) {
  //   // const editor = unref(editorRef);
  //   const editor = tinymce.get(unref(tinymceId));
  //   if (!editor) {
  //     return;
  //   }
  //   const content = editor?.getContent() ?? '';
  //   const val = content?.replace(getUploadingImgName(name), `<img src="${url}"/>`) ?? '';
  //   setValue(editor, val);
  // }

  // function getUploadingImgName(name: string) {
  //   return `[uploading:${name}]`;
  // }
</script>
<style lang="less">
  @prefix-cls: ~'@{namespace}-tinymce-container';

  .@{prefix-cls} {
    position: relative;
    line-height: normal;

    textarea {
      visibility: hidden;
      z-index: -1;
    }
  }
</style>
